import { BaseGameService } from './base/BaseGameService';
import { HealthCheckResult } from './base/IGameService';
import { BagRepository } from '../repository/BagRepository';
import { Item, Bag } from '../shared/face';

/**
 * 统一的背包服务 - 新架构示例
 * 展示如何使用BaseGameService创建现代化服务
 */
export class UnifiedBagService extends BaseGameService {
    readonly serviceName = 'UnifiedBagService';
    readonly dependencies = ['BagRepository'];
    
    private bagRepository?: BagRepository;

    /**
     * 服务初始化
     */
    protected async onInit(): Promise<void> {
        this.log('info', 'Initializing UnifiedBagService...');
        
        // 获取依赖服务
        this.bagRepository = this.getService<BagRepository>('BagRepository');
        
        // 执行初始化逻辑
        await this.validateRepository();
        
        this.log('info', 'UnifiedBagService initialized successfully');
    }

    /**
     * 服务销毁
     */
    protected async onDestroy(): Promise<void> {
        this.log('info', 'Destroying UnifiedBagService...');
        
        // 清理资源
        this.bagRepository = undefined;
        
        this.log('info', 'UnifiedBagService destroyed successfully');
    }

    /**
     * 健康检查
     */
    protected async onHealthCheck(): Promise<HealthCheckResult> {
        try {
            // 检查Repository连接
            if (!this.bagRepository) {
                return {
                    healthy: false,
                    message: 'BagRepository not available',
                    timestamp: Date.now()
                };
            }

            // 执行简单的数据库连接测试
            const testResult = await this.bagRepository.healthCheck();
            
            return {
                healthy: testResult.healthy,
                message: testResult.healthy ? 'Service healthy' : `Repository health check failed: ${testResult.message}`,
                timestamp: Date.now(),
                details: {
                    repositoryStatus: testResult
                }
            };
        } catch (error) {
            return {
                healthy: false,
                message: `Health check failed: ${(error as Error).message}`,
                timestamp: Date.now()
            };
        }
    }

    // ==================== 业务方法 ====================

    /**
     * 添加物品到背包
     */
    async addItem(playerId: string, item: Item): Promise<{ success: boolean; message: string }> {
        return this.recordCall('addItem', async () => {
            if (!this.bagRepository) {
                throw new Error('BagRepository not available');
            }

            this.log('info', `Adding item to bag for player ${playerId}`, { 
                itemName: item.name, 
                itemCount: item.count 
            });

            try {
                // 获取玩家背包
                const bag = await this.bagRepository.getBagByPlayerId(playerId);
                
                // 添加物品
                const addResult = bag.addItem(item);
                
                if (addResult.success) {
                    // 保存背包
                    await this.bagRepository.saveBag(playerId, bag);
                    
                    this.log('info', `Item added successfully for player ${playerId}`);
                    return {
                        success: true,
                        message: '物品添加成功'
                    };
                } else {
                    this.log('warn', `Failed to add item for player ${playerId}: ${addResult.message}`);
                    return {
                        success: false,
                        message: addResult.message
                    };
                }
            } catch (error) {
                this.log('error', `Error adding item for player ${playerId}`, error);
                throw error;
            }
        });
    }

    /**
     * 移除物品
     */
    async removeItem(playerId: string, itemName: string, count: number): Promise<{ success: boolean; message: string }> {
        return this.recordCall('removeItem', async () => {
            if (!this.bagRepository) {
                throw new Error('BagRepository not available');
            }

            this.log('info', `Removing item from bag for player ${playerId}`, { 
                itemName, 
                count 
            });

            try {
                const bag = await this.bagRepository.getBagByPlayerId(playerId);
                const removeResult = bag.removeItem(itemName, count);
                
                if (removeResult.success) {
                    await this.bagRepository.saveBag(playerId, bag);
                    
                    this.log('info', `Item removed successfully for player ${playerId}`);
                    return {
                        success: true,
                        message: '物品移除成功'
                    };
                } else {
                    this.log('warn', `Failed to remove item for player ${playerId}: ${removeResult.message}`);
                    return {
                        success: false,
                        message: removeResult.message
                    };
                }
            } catch (error) {
                this.log('error', `Error removing item for player ${playerId}`, error);
                throw error;
            }
        });
    }

    /**
     * 获取背包内容
     */
    async getBagContents(playerId: string): Promise<Bag> {
        return this.recordCall('getBagContents', async () => {
            if (!this.bagRepository) {
                throw new Error('BagRepository not available');
            }

            this.log('info', `Getting bag contents for player ${playerId}`);

            try {
                const bag = await this.bagRepository.getBagByPlayerId(playerId);
                this.log('info', `Bag contents retrieved for player ${playerId}`, { 
                    itemCount: bag.items.size 
                });
                return bag;
            } catch (error) {
                this.log('error', `Error getting bag contents for player ${playerId}`, error);
                throw error;
            }
        });
    }

    /**
     * 检查物品是否存在
     */
    async hasItem(playerId: string, itemName: string, requiredCount: number = 1): Promise<boolean> {
        return this.recordCall('hasItem', async () => {
            if (!this.bagRepository) {
                throw new Error('BagRepository not available');
            }

            try {
                const bag = await this.bagRepository.getBagByPlayerId(playerId);
                const hasItem = bag.hasItem(itemName, requiredCount);
                
                this.log('info', `Item check for player ${playerId}`, { 
                    itemName, 
                    requiredCount, 
                    hasItem 
                });
                
                return hasItem;
            } catch (error) {
                this.log('error', `Error checking item for player ${playerId}`, error);
                throw error;
            }
        });
    }

    /**
     * 使用物品
     */
    async useItem(playerId: string, itemName: string, count: number = 1): Promise<{ success: boolean; message: string; effects?: any[] }> {
        return this.recordCall('useItem', async () => {
            if (!this.bagRepository) {
                throw new Error('BagRepository not available');
            }

            this.log('info', `Using item for player ${playerId}`, { 
                itemName, 
                count 
            });

            try {
                const bag = await this.bagRepository.getBagByPlayerId(playerId);
                
                // 检查物品是否存在
                if (!bag.hasItem(itemName, count)) {
                    return {
                        success: false,
                        message: '物品数量不足'
                    };
                }

                // 移除物品
                const removeResult = bag.removeItem(itemName, count);
                if (!removeResult.success) {
                    return {
                        success: false,
                        message: removeResult.message
                    };
                }

                // 保存背包
                await this.bagRepository.saveBag(playerId, bag);

                // 这里可以添加物品使用效果的处理逻辑
                const effects = await this.processItemEffects(playerId, itemName, count);

                this.log('info', `Item used successfully for player ${playerId}`);
                return {
                    success: true,
                    message: '物品使用成功',
                    effects
                };
            } catch (error) {
                this.log('error', `Error using item for player ${playerId}`, error);
                throw error;
            }
        });
    }

    // ==================== 私有方法 ====================

    /**
     * 验证Repository
     */
    private async validateRepository(): Promise<void> {
        if (!this.bagRepository) {
            throw new Error('BagRepository not initialized');
        }

        // 执行Repository健康检查
        const healthResult = await this.bagRepository.healthCheck();
        if (!healthResult.healthy) {
            throw new Error(`BagRepository health check failed: ${healthResult.message}`);
        }

        this.log('info', 'BagRepository validation passed');
    }

    /**
     * 处理物品使用效果
     */
    private async processItemEffects(playerId: string, itemName: string, count: number): Promise<any[]> {
        // 这里可以集成到物品效果系统
        // 目前返回空数组作为占位
        this.log('info', `Processing item effects for ${itemName} x${count}`);
        return [];
    }
}
